package com.kwq.shixi.util;


import com.kwq.shixi.model.ExportData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author gothiconezq
 * 导出excel工具类
 */
public class ExportExcelUtil {
    /**
     * 空值响应
     * @param response
     * @throws Exception
     */
    public static void nullResponse(HttpServletResponse response, int type) throws Exception{
        OutputStream os = response.getOutputStream();
        if(type==1) {
            os.write("请传入查询参数！".getBytes("utf-8"));
        }else if(type==2){
            os.write("未查询到相应数据！".getBytes("utf-8"));
        }
        response.setStatus(404);
        return;
    }

    public static void exportExcel(HttpServletResponse response, ExportData data) throws Exception {
        // 如果文件名是英文名不需要加编码格式，如果是中文名需要添加"iso-8859-1"防止乱码
        response.setHeader("Content-Disposition", "attachment; filename=" + new String((data.getFileName()).getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(data.getFileName(), "utf-8"));
        exportResultExcel(data, response.getOutputStream());
    }
    public static void exportResultExcel(ExportData data, OutputStream out) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getSheetName();
            sheetName = sheetName==null?"Sheet1":sheetName;
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);
            wb.write(out);
        } finally {
            wb.close();
        }
    }
    /**
     * 写表
     * @param wb
     * @param sheet   表名
     * @param data    数据
     */
    private static void writeExcel(XSSFWorkbook wb, XSSFSheet sheet, ExportData data) {
        String[] titles = data.getTitles();
        if(titles!=null&&titles.length>0){
            int colLength = titles.length;
            // 设定自适应列宽  先不看
           sheet.autoSizeColumn(1, true);

            // 设定表头
            Row row1 = sheet.createRow(0);
            // 设置表头高度
            row1.setHeight((short) 400);
            for(int t=0;t<colLength;t++){
                Cell cell1 = row1.createCell(t);
                cell1.setCellValue(titles[t]);
                //设置单元格的样式
               setXSSFCellStyle(wb, cell1, true, (short) 11, false, false, true);
                //设置某一行每一个单元格的宽度
                sheet.setColumnWidth(t, titles[t].getBytes().length*4*256);
            }
            //数据处理
            List<String[]> rowList = data.getList();
            if(rowList!=null&&rowList.size()>0){
                for(int r=0;r<rowList.size();r++){
                    String[] rowArr = rowList.get(r);
                    if(rowArr!=null&&rowArr.length>0){
                        Row row = sheet.createRow(r+1);
                        for(int c=0;c<rowArr.length;c++){
                            Cell cell = row.createCell(c);
                            cell.setCellValue(rowArr[c]);
                            //先不看
                          setXSSFCellStyle(wb, cell, false, (short) 11, false, false, true);
                        }
                    }
                }
            }
        }

    }
    /**
     * 设置单元格样式
     * @param xwb 工作簿
     * @param xc 单元格
     * @param bold 粗体
     * @param fontSize 字体大小
     * @param setBack 背景颜色
     * @param setWrap 自动换行
     * @param setBorder 边框
     */
    private static void setXSSFCellStyle(XSSFWorkbook xwb, Cell xc, boolean bold, Short fontSize, boolean setBack, boolean setWrap, boolean setBorder){
        // 创建单元格样式
        XSSFCellStyle style = xwb.createCellStyle();
        // 设置单元格内容水平、垂直居中
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 创建字体
        XSSFFont font = xwb.createFont();
        // 统一字体为黑体
        font.setFontName("黑体");
        // 是否为粗体
        font.setBold(bold);
        // 设置字体大小
        fontSize = fontSize==null?11:fontSize;
        font.setFontHeightInPoints(fontSize);
        style.setFont(font);
        // 设置背景颜色
        if(setBack) {
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        }
        // 设置自动换行
        style.setWrapText(setWrap);
        //设置边框
        if(setBorder) {
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
        }
        // 为特定单元格设置样式
        xc.setCellStyle(style);
    }


}
